package com.link.play.fit.ai.bean

import com.google.gson.Gson
import com.link.play.fit.ai.utils.DateEx
import java.io.Serializable

/**
 *  serving 保存比率, 数量 /  servingTypebean. metricAmount
 *  所有数值都要计算出来,之后在传出去
 *
 *
 */
data class InfoIngredientsBean(
    var name: String = "",
    val brand: String = "",

    var servings: Double = 0.0, //计算营养物质的数量的系数 从接口 ,如果是按份数计算,就保存的份数
    val unitLabel: String = "",
    val metricAmount: Double = 0.0,
    val metricUnit: String = "",


    var calories: Double = 0.0,
    var carbs: Double = 0.0,
    var protein: Double = 0.0,
    var fats: Double = 0.0,

    val mass: Double = 0.0,
    var servingTypeId: String = "", // 选中的 servingType
    var servingTypes: MutableList<ServingTypeBean> = mutableListOf<ServingTypeBean>(),
    //本地要用的
    var timeMillisencond: String = "",//时间戳
    //修改数值的时候更新他
    var localCalories: Double = 0.0,//本地的
    var localProtein: Double = 0.0,//本地的
    var localCarbs: Double = 0.0,//本地的
    var localFats: Double = 0.0,//本地的
) : Serializable

fun InfoIngredientsBean.toRecentlyEatenData(): RecentlyEatenData {
    val red = RecentlyEatenData()
    red.foodName = this.name

    if (this.localCalories != 0.0) {
        red.caloriesDaily =
            (this.localCalories * this.servings).toInt()
    } else {
        red.caloriesDaily =
            (this.calories * this.servings).toInt()
    }
    if (this.localProtein != 0.0) {
        red.proteinDaily =
            (this.localProtein * this.servings).toInt()
    } else {
        red.proteinDaily =
            (this.protein * this.servings).toInt()
    }
    if (this.localCarbs != 0.0) {
        red.carbsDaily =
            (this.localCarbs * this.servings).toInt()
    } else {
        red.carbsDaily =
            (this.carbs * this.servings).toInt()
    }
    if (this.localFats != 0.0) {
        red.fatsDaily =
            (this.localFats * this.servings).toInt()
    } else {
        red.fatsDaily =
            (this.fats * this.servings).toInt()
    }

    red.createTime = this.timeMillisencond
    red.ingredients = Gson().toJson(this)
    red.timeDay = DateEx.getDayOfMonth()
    red.type = 4 //接口获取的食物
    return red
}

//获取ingredients对象
fun getIngredients(i: String): InfoIngredientsBean? {
    runCatching {
        val ing = Gson().fromJson<InfoIngredientsBean>(i, InfoIngredientsBean::class.java)
        return ing
    }
    return null
}

//获取选中的servingType对象
fun getServingType(i: String): ServingTypeBean? {
    runCatching {
        val ing = getIngredients(i)
        val stb = ing?.servingTypes?.find {
            if (it.id == ing?.servingTypeId) {
                return@find true
            }
            return@find false
        }
        return stb
    }
    return null
}